package com.lele.config.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lele.pojo.Admin;
import com.lele.pojo.Menu;
import com.lele.pojo.vo.LoginAdminVo;
import com.lele.service.IAdminService;
import com.lele.service.IMenuService;
import com.lele.utils.JWTUtil;
import com.lele.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;

@RestController
public class LoginController {

    @Resource
    private IAdminService adminService;
    @Resource
    private IMenuService menuService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private JWTUtil jwtUtil;
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginAdminVo adminVo, HttpServletRequest request){
        String username = adminVo.getUsername();
        String password = adminVo.getPassword();
        String code = adminVo.getCode();
        String flag = adminVo.getFlag();
        BoundHashOperations boundHashOps = redisTemplate.boundHashOps("kaptcha:");
        String captcha = (String) boundHashOps.get(flag);
        if(StringUtils.isEmpty(code)||!code.equals(captcha)){
            return Result.ERROR("验证码错误");
        }
        if(StringUtils.isEmpty(username)) {
            return Result.ERROR("用户名为空");
        }
        //用户名进行比较，查出来对应的信息
        UserDetails userDetails =userDetailsService.loadUserByUsername(username);
        //使用PasswordEncoding实现密码的比较
        if(userDetails==null||!passwordEncoder.matches(password, userDetails.getPassword())){
            return Result.ERROR("用户名或密码错误");
        }
        if(!userDetails.isEnabled()){
            return Result.ERROR("该用户不可用");
        }
        //更新springsecurity登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = jwtUtil.createToken(userDetails);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead","Bearer");
        return Result.OK(map);
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.OK("退出登录成功");
    }

    /**
     * 获取登录用户的信息
     * @param principal
     * @return
     */
    @GetMapping("admin/info")
    public Admin getAdminInfo(Principal principal){
        if(principal==null){
            return null;
        }
        Admin admin=adminService.getAdminInfoByPrincipal(principal);
        //TODO 设置登录用户的Roles信息
        admin.setRoles(adminService.getAdminWithRoles(admin.getId()));
        return admin;
    }


    @GetMapping("/employee/basic/hello1")
    public String hello1(){
        return "可以访问";
    }
    @GetMapping("/employee/advanced/hello2")
    public String hello2(){
        return "不可以访问";
    }


    @GetMapping("getMenu")
    public List<Menu> getMenu(){
        List<Menu> withRole = menuService.getMenuWithRole();
        return withRole;
    }

}
